package com.rycx.facefeatureclient.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.rycx.facefeatureclient.bean.AjaxResult;
import com.rycx.facefeatureclient.util.Base64Util;
import com.rycx.facefeatureclient.util.OKHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

/**
 * 视觉智能
 * https://zhuanlan.zhihu.com/p/706250420
 */
@RestController
@RequestMapping("/saas/image")
@Slf4j
public class ImageController {

    @Value("${saas.facefeature-api}")
    private String facefeatureApi;

    @Value("${saas.queryquue-api}")
    private String queryquueApi;

    @Value("${saas.addque-api}")
    private String addqueApi;

    @Value("${saas.delque-api}")
    private String delqueApi;


    @PostMapping("/faceFeatureFB")
    public AjaxResult faceFeatureFB(@RequestBody Map<String, String> param) {
        // 参数基础验证
        String token = param.get("token");
        String sourceDir = param.get("sourceDir");
        String targetDir = param.get("targetDir");
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(sourceDir) || StringUtils.isEmpty(targetDir)) {
            return AjaxResult.error("参数缺失");
        }
        Map<String, String> queryQueParam = new HashMap<>();
        queryQueParam.put("token", token);
        String queryqueResultStr = OKHttpUtil.postJsonParams(queryquueApi, JSON.toJSONString(queryQueParam));
        JSONObject queryqueResult = JSONObject.parseObject(queryqueResultStr);
        JSONArray ques = queryqueResult.getJSONArray("data");
        if (ques != null && ques.size() > 0) {
            return AjaxResult.error("当前有分类任务正在进行，请等待该任务结束");
        }
        Map<String, String> addQueParam = new HashMap<>();
        addQueParam.put("token", token);
        String addResultStr = OKHttpUtil.postJsonParams(addqueApi, JSON.toJSONString(addQueParam));
        JSONObject addResult = JSONObject.parseObject(addResultStr);
        String male_yellow_down35 = targetDir + "/男性" + "/黄色皮肤" + "/35岁以下";
        String male_yellow_up35 = targetDir + "/男性" + "/黄色皮肤" + "/35~80岁";
        String male_brown_down35 = targetDir + "/男性" + "/棕色皮肤" + "/35岁以下";
        String male_brown_up35 = targetDir + "/男性" + "/棕色皮肤" + "/35~80岁";
        String male_black_down35 = targetDir + "/男性" + "/黑色皮肤" + "/35岁以下";
        String male_black_up35 = targetDir + "/男性" + "/黑色皮肤" + "/35~80岁";
        String male_white_down35 = targetDir + "/男性" + "/白色皮肤" + "/35岁以下";
        String male_white_up35 = targetDir + "/男性" + "/白色皮肤" + "/35~80岁";
        String female_yellow_down35 = targetDir + "/女性" + "/黄色皮肤" + "/35岁以下";
        String female_yellow_up35 = targetDir + "/女性" + "/黄色皮肤" + "/35~80岁";
        String female_brown_down35 = targetDir + "/女性" + "/棕色皮肤" + "/35岁以下";
        String female_brown_up35 = targetDir + "/女性" + "/棕色皮肤" + "/35~80岁";
        String female_black_down35 = targetDir + "/女性" + "/黑色皮肤" + "/35岁以下";
        String female_black_up35 = targetDir + "/女性" + "/黑色皮肤" + "/35~80岁";
        String female_white_down35 = targetDir + "/女性" + "/白色皮肤" + "/35岁以下";
        String female_white_up35 = targetDir + "/女性" + "/白色皮肤" + "/35~80岁";
        String more_than_1 = targetDir + "/多人";
        String not_human = targetDir + "/非人";
        String fail_img = targetDir + "/异常";
        new File(male_yellow_down35).mkdirs();
        new File(male_yellow_up35).mkdirs();
        new File(male_brown_down35).mkdirs();
        new File(male_brown_up35).mkdirs();
        new File(male_black_down35).mkdirs();
        new File(male_black_up35).mkdirs();
        new File(male_white_down35).mkdirs();
        new File(male_white_up35).mkdirs();
        new File(female_yellow_down35).mkdirs();
        new File(female_yellow_up35).mkdirs();
        new File(female_brown_down35).mkdirs();
        new File(female_brown_up35).mkdirs();
        new File(female_black_down35).mkdirs();
        new File(female_black_up35).mkdirs();
        new File(female_white_down35).mkdirs();
        new File(female_white_up35).mkdirs();
        new File(more_than_1).mkdirs();
        new File(not_human).mkdirs();
        new File(fail_img).mkdirs();
        File[] images = new File(sourceDir).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                //支持PNG、JPG、JPEG、BMP，不支持 GIF 图片
                String lowerName = name.toLowerCase();
                if (lowerName.endsWith(".png") || lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".bmp")) {
                    return true;
                } else {
                    File file = new File(dir.getAbsolutePath() + "/" + name);
                    if (!file.isDirectory()) {
                        //移入分类异常目录
                        moveFile(file, fail_img);
                    }
                    return false;
                }
            }
        });
        JSONObject featureParam = new JSONObject();
        featureParam.put("token", token);
        for (File image : images) {
            try {
                featureParam.put("imageData", Base64Util.imageToBase64Str(image));
                String featureResultStr = OKHttpUtil.postJsonParams(facefeatureApi, JSON.toJSONString(featureParam));
                JSONObject idenResult = JSONObject.parseObject(featureResultStr);
                Integer code = idenResult.getInteger("code");
                if (code == 500) {
                    moveFile(image, fail_img);
                }
                String dir = idenResult.getString("msg");
                if (dir.equals("fail_img")) {
                    moveFile(image, fail_img);
                } else if (dir.equals("not_human")) {
                    moveFile(image, not_human);
                } else if (dir.equals("more_than_1")) {
                    moveFile(image, more_than_1);
                } else {
                    if (dir.equals("male_yellow_down35")) {
                        moveFile(image, male_yellow_down35);
                    }
                    if (dir.equals("male_yellow_up35")) {
                        moveFile(image, male_yellow_up35);
                    }
                    if (dir.equals("male_brown_down35")) {
                        moveFile(image, male_brown_down35);
                    }
                    if (dir.equals("male_brown_up35")) {
                        moveFile(image, male_brown_up35);
                    }
                    if (dir.equals("male_black_down35")) {
                        moveFile(image, male_black_down35);
                    }
                    if (dir.equals("male_black_up35")) {
                        moveFile(image, male_black_up35);
                    }
                    if (dir.equals("male_white_down35")) {
                        moveFile(image, male_white_down35);
                    }
                    if (dir.equals("male_white_up35")) {
                        moveFile(image, male_white_up35);
                    }
                    if (dir.equals("female_yellow_down35")) {
                        moveFile(image, female_yellow_down35);
                    }
                    if (dir.equals("female_yellow_up35")) {
                        moveFile(image, female_yellow_up35);
                    }
                    if (dir.equals("female_brown_down35")) {
                        moveFile(image, female_brown_down35);
                    }
                    if (dir.equals("female_brown_up35")) {
                        moveFile(image, female_brown_up35);
                    }
                    if (dir.equals("female_black_down35")) {
                        moveFile(image, female_black_down35);
                    }
                    if (dir.equals("female_black_up35")) {
                        moveFile(image, female_black_up35);
                    }
                    if (dir.equals("female_white_down35")) {
                        moveFile(image, female_white_down35);
                    }
                    if (dir.equals("female_white_up35")) {
                        moveFile(image, female_white_up35);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                //移入分类异常目录
                moveFile(image, fail_img);
            }
        }
        String delResultStr = OKHttpUtil.postJsonParams(delqueApi, JSON.toJSONString(param));
        JSONObject delResult = JSONObject.parseObject(delResultStr);
        return AjaxResult.success("分类完成");
    }

    public void moveFile(File image, String targetDir) {
        System.out.println("image: " + image.getName());
        System.out.println("targetDir: " + targetDir);
        Path source = Paths.get(image.getAbsolutePath());
        Path target = Paths.get(targetDir + "/" + image.getName());
        try {
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error(image.getName() + " 移动过程出错，已跳过");
            e.printStackTrace();
        }
    }
}
